package com.hanrui.android.fragment.message.audit.performance;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.ToastUtils;
import com.hanrui.android.R;
import com.hanrui.android.activity.TermActivity;
import com.hanrui.android.library.base.BaseFragment;
import com.hanrui.android.constant.Constant;
import com.hanrui.android.model.GetNextActvityBean;
import com.hanrui.android.model.PerformanceBizDetailBean;
import com.hanrui.android.net.contract.message.audit.performance.PerformanceBizContract;
import com.hanrui.android.net.presenter.message.audit.performance.PerformanceBizPresenter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 绩效审批流程
 */

public class PerformanceBizFragment extends BaseFragment<PerformanceBizPresenter> implements PerformanceBizContract.View {

    @BindView(R.id.next)
    LinearLayout nextLl;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.name_go)
    ImageView nameGo;
    @BindView(R.id.bm_ll)
    LinearLayout bmLl;
    @BindView(R.id.bm)
    TextView bm;
    @BindView(R.id.bm_go)
    ImageView bmGo;
    @BindView(R.id.reson_ll)
    LinearLayout resonLl;
    @BindView(R.id.reson)
    EditText reson;
    @BindView(R.id.ll_addview)
    LinearLayout lladdview;

    String taskId,procInsId,bizId;
    String transitionId = "";
    String nextAssigneeList = "";
    String performanceList = "";

    GetNextActvityBean.NextActivityBean bean;

    OptionsPickerView pvOptions;

    ArrayList<GetNextActvityBean.NextActivityBean.NextAssigneeListBean> dataList = new ArrayList<>();

    JSONArray jsonArray;

    List<PerformanceBizDetailBean.DetailBean.PerformanceListBean> performanceBeanList;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_performancebiz;
    }

    @Override
    protected void initInjector() { mFragmentComponent.inject(this); }

    @Override
    protected void initView(View view) {

        taskId = getArguments().getString("taskId");
        procInsId = getArguments().getString("procInsId");
        bizId = getArguments().getString("bizId");

        mPresenter.getNextActivity(getActivity(),taskId,procInsId,bizId);

    }

    //实例化
    public static PerformanceBizFragment newInstance(String taskId, String procInsId, String bizId) {
        PerformanceBizFragment fragment = new PerformanceBizFragment();
        Bundle bundle = new Bundle();
        bundle.putString("taskId", taskId);
        bundle.putString("procInsId", procInsId);
        bundle.putString("bizId", bizId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void getNextActivity(GetNextActvityBean data) {

        name.setText(data.getNextActivity().getName());
        bean = data.getNextActivity();

        if (bean.getType().equals("endEvent")) {

            bmLl.setVisibility(View.GONE);
            resonLl.setVisibility(View.GONE);
            reson.setText("");
            mPresenter.performanceBizDetail(getActivity(),taskId,procInsId,bizId);
            return;

        		}


        if (null != bean.getTransitions() && bean.getTransitions().size() > 0) {

            List<GetNextActvityBean.NextActivityBean.TransitionsListBean> transitionsList = bean.getTransitions();

            name.setText(transitionsList.get(0).getName());
            transitionId = transitionsList.get(0).getId();

            if (null != transitionsList.get(0).getNextAssigneeList() && transitionsList.get(0).getNextAssigneeList().size() >0) {

                bm.setText(transitionsList.get(0).getNextAssigneeList().get(0).getName());
                nextAssigneeList = transitionsList.get(0).getNextAssigneeList().get(0).getId();

                getTransitionNextActivity(transitionsList.get(0).getNextAssigneeList());

            }else {

                bmLl.setVisibility(View.GONE);
                nextAssigneeList = "";

            }

            if (transitionsList.size() == 1) {

                name.setText(bean.getName());
                nextLl.setEnabled(false);
                nameGo.setVisibility(View.GONE);


            		}else {

                nextLl.setEnabled(true);
                nameGo.setVisibility(View.VISIBLE);

                pvOptions = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        transitionId = bean.getTransitions().get(options1).getId();
                        name.setText(bean.getTransitions().get(options1).getPickerViewText());
                        if (null != bean.getTransitions().get(options1).getNextAssigneeList() &&
                                bean.getTransitions().get(options1).getNextAssigneeList().size() > 0) {

                            bmLl.setVisibility(View.VISIBLE);
                            bm.setText(bean.getTransitions().get(options1).getNextAssigneeList().get(0).getName());
                            nextAssigneeList = bean.getTransitions().get(options1).getNextAssigneeList().get(0).getId();
                            getTransitionNextActivity(bean.getTransitions().get(options1).getNextAssigneeList());

                        }else {

                            bmLl.setVisibility(View.GONE);
                            bm.setText("");
                            bm.setHint("请选择");
                            nextAssigneeList = "";
                        }

                    }
                }).build();
                pvOptions.setPicker(bean.getTransitions());

            }

        		}else {


            if (null != bean.getNextAssigneeList() && bean.getNextAssigneeList().size() > 0) {

                nextAssigneeList = bean.getNextAssigneeList().get(0).getId();
                bm.setText(bean.getNextAssigneeList().get(0).getName());
                getTransitionNextActivity(bean.getNextAssigneeList());

            }else {

                bmLl.setVisibility(View.GONE);
                nextAssigneeList = "";
            }



        }

    }


    private void getTransitionNextActivity(List<GetNextActvityBean.NextActivityBean.NextAssigneeListBean> nextAssigneeList) {

        if (nextAssigneeList.size() == 1) {

            bmLl.setEnabled(false);
            bmGo.setVisibility(View.GONE);

        }else {

            bmLl.setEnabled(true);
            bmGo.setVisibility(View.VISIBLE);
            dataList.clear();
            dataList.addAll(nextAssigneeList);
            bmLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    TermActivity.start(PerformanceBizFragment.this, Constant.nextactivity,dataList,false);
                }
            });

        }

    }

    @Override
    public void performanceBizApproval(int code) {
        if (code == 1) {

            ToastUtils.showShort("提交成功");
            getActivity().finish();

        		}else {

            ToastUtils.showShort("提交失败");
        }

    }

    @Override
    public void performanceBizDetail(PerformanceBizDetailBean data) {

        if (null != data && null != data.getDetail().getPerformanceList() && data.getDetail().getPerformanceList().size() > 0) {

            performanceBeanList = data.getDetail().getPerformanceList();

            lladdview.setVisibility(View.VISIBLE);
            for (int i = 0; i < data.getDetail().getPerformanceList().size(); i++) {

                    addViewItem(data.getDetail().getPerformanceList().get(i));

            }

        		}


    }


    @OnClick({R.id.next_ll,R.id.login_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.next_ll:
                if (null != pvOptions)
                    pvOptions.show();
                break;
            case R.id.login_out:
                getPerformanceList();
                //mPresenter.performanceBizApproval(getActivity(),nextAssigneeList,taskId,procInsId,bizId,transitionId,reson.getText().toString());
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constant.nextactivity:
                if (null != data) {
                    String result = data.getStringExtra("data");
                    String countING = data.getStringExtra("id");
                    if (null != result && !"".equals(result)) {
                        bm.setText(result);
                    }
                    nextAssigneeList = countING;
                }
                break;
        }
    }



    //添加ViewItem
    private void addViewItem(final PerformanceBizDetailBean.DetailBean.PerformanceListBean bean) {
        View hotelEvaluateView = View.inflate(getActivity(), R.layout.item_performancebiz, null);
        TextView minTitle = hotelEvaluateView.findViewById(R.id.min_title);
        TextView check = hotelEvaluateView.findViewById(R.id.check);
        TextView baseScore = hotelEvaluateView.findViewById(R.id.base_score);
        TextView selfScore = hotelEvaluateView.findViewById(R.id.self_score);


        minTitle.setText("打分");
        check.setText(bean.getRules());
        baseScore.setText(bean.getBaseScore());
        selfScore.setText(bean.getSelfScore());


        lladdview.addView(hotelEvaluateView);
    }


    private void getPerformanceList(){

        if (jsonArray == null) {

            jsonArray = new JSONArray();
        }

        for (int i = 0; i < lladdview.getChildCount(); i++) {

            View childAt = lladdview.getChildAt(i);
            TextView leaderScore = childAt.findViewById(R.id.leader_score);

            String str = leaderScore.getText().toString();

            if (TextUtils.isEmpty(str)) {

                ToastUtils.showShort("请输入分数");
                return;

            }

            JSONObject tmpObj = new JSONObject();

            try {
                tmpObj.put("id",performanceBeanList.get(i).getId());
                tmpObj.put("headScore",str);
                jsonArray.put(tmpObj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        performanceList = jsonArray.toString();
        mPresenter.performanceBizApproval(getActivity(),nextAssigneeList,taskId,procInsId,bizId,transitionId,reson.getText().toString(),performanceList);
        jsonArray = null;
    }
}
